package com.jboltai.capability.text.extract.pdf;

import com.jboltai.capability.text.ContentInfo;
import com.jboltai.capability.text.ContentType;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.text.PDFTextStripper;
import org.apache.pdfbox.text.TextPosition;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

public class TextStripper extends PDFTextStripper {


    private List<ContentInfo> texts = new ArrayList<>();


    public TextStripper() throws IOException {
    }


    public List<ContentInfo> readTextInfo(PDDocument doc) {
        try {
            texts.clear();
            super.getText(doc);
            return texts;
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    protected void writeString(String text, List<TextPosition> textPositions) throws IOException {

        super.writeString(text, textPositions);
        texts.add(new ContentInfo(ContentType.TEXT, text.replaceAll("\\^\\[\\d+\\]\\^", ""), textPositions.get(0).getX(), textPositions.get(0).getY()));

    }


    @Override
    protected void writeLineSeparator() throws IOException {

        super.writeLineSeparator();

    }

    @Override
    protected void writeParagraphSeparator() throws IOException {
        texts.add(new ContentInfo(ContentType.TEXT, "\n", 0, 0));
        super.writeParagraphSeparator();
    }



}
